<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>

      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="name"
      />
      <el-button type="primary" @click="queryByName">查询</el-button>
    </div>

    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addEnterprise')" v-auth="'park:enterprise:add_edit'">添加企业</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="expandChange">
        <el-table-column type="expand">
          <template #default>
            <el-table :data="rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template slot-scope="scope">
                  <el-tag :type="rentState[scope.row.status]">{{
                    rentState[scope.row.status]
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text" :disabled="rentState[scope.row.status]=='已退租'?true:false" @click="cancelRent(scope.row.id)">退租</el-button>

                  <el-button size="mini" type="text" @click="delRent(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" v-auth="'park:rent:add_surrender'" @click="showContract(scope.row.id)">添加合同</el-button>
            <el-button size="mini" type="text" v-auth="'park:enterprise:query'" @click="$router.push({path: '/enterpriseDetail',query: { id: scope.row.id }})">查看</el-button>
            <el-button size="mini" type="text" v-auth="'park:enterprise:add_edit'" @click="$router.push({path:'/addEnterprise',query:{id:scope.row.id}})">编辑</el-button>
            <el-button size="mini" type="text" v-auth="'park:enterprise:remove'" @click="delEnterprise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="pageChangeHandler"
      />
    </div>
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container"></div>
      <el-form
        ref="addForm"
        :model="rentForm"
        :rules="rentRules"
        label-position="top"
      >
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-model="rentForm.buildingId" placeholder="请选择">
            <el-option
              v-for="item in buildList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="租赁起止日期" prop="rentTime">
          <el-date-picker
            v-model="rentForm.rentTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item label="租赁合同" prop="contractId">
          <el-upload action="#" :http-request="upLoadContract">
            <el-button size="small" type="primary" plain
              >上传合同文件</el-button
            >

            <div slot="tip" class="el-upload__tip">
              支持扩展名：.doc .docx .pdf, 文件大小不超过5M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>

        <el-button size="mini" type="primary" @click="uploadContractForm"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEnterPriseListApi,
  getRentApi,
  getRentBuildListAPI,
  upLoad,
  addContractApi,
  delEnterpriseApi,
  delRentApi,
  cancelRentApi
} from "@/api/enterprise";

export default {
  data() {
    return {
      rentDialogVisible: false,
      list: [],
      page: 1,
      pageSize: 5,
      total: 0,
      name: "",
      rentList: [],
      buildList: [],
      rentState: {
        0: "待生效",
        1: "生效中",
        2: "已到期",
        3: "已退租",
      },
      rentRules: {
        buildingId: [
          { required: true, message: "请选择楼宇", trigger: "change" },
        ],
        rentTime: [
          { required: true, message: "请选择租赁日期", trigger: "change" },
        ],
        contractId: [{ required: true, message: "请上传合同文件" }],
      },
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: "", // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [], // 合同时间
      },
    };
  },
  created() {
    this.getEnterPriseList();
  },
  methods: {
   cancelRent(id){
      this.$confirm('是否退租', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await cancelRentApi(id)
          await this.getEnterpriseList()
          this.$message({
            type: 'success',
            message: '退租成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
    },
    async showContract(id) {
      this.rentDialogVisible = true;
      const res = await getRentBuildListAPI();
      this.buildList = res.data;
      this.rentForm.enterpriseId = id;
    },
    closeDialog() {
      this.rentDialogVisible = false;
    },
    async getEnterPriseList() {
      let res = await getEnterPriseListApi({
        page: this.page,
        pageSize: this.pageSize,
      });
      this.list = res.data.rows;
      this.total = res.data.total;
    },
    async expandChange(row, expandedRows) {
      let index = expandedRows.findIndex((item) => (item.id = row.id));
      if (index > -1) {
        let res = await getRentApi(row.id);
        this.rentList = res.data;
      }
    },
    async upLoadContract(params) {
      let { file } = params;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "contract");
      let res = await upLoad(formData);
      console.log(res.data);
      this.rentForm.contractId = res.data.id;
      this.rentForm.contractUrl = res.data.url;
      this.$refs.addForm.validate("contractId");
    },
    async uploadContractForm() {
      const obj = {
        buildingId: this.rentForm.buildingId,
        startTime: this.rentForm.rentTime[0],
        endTime: this.rentForm.rentTime[1],
        contractUrl: this.rentForm.contractUrl,
        contractId: this.rentForm.contractId,
        type: this.rentForm.type,
        enterpriseId: this.rentForm.enterpriseId,
      };
      await addContractApi(obj);
      this.$refs.addForm.resetFields();
      await this.showContract(this.rentForm.buildingId);
      this.closeDialog();
      this.$message.success("新增合同成功");
    },
    pageChangeHandler(val) {
      console.log(val);
      this.page = val;
      this.getEnterPriseList();
    },
    async queryByName() {
      let obj = {
        page: this.page,
        pageSize: this.pageSize,
        name: this.name,
      };
      let res = await getEnterPriseListApi(obj);
      this.list = res.data.rows;
      this.total = res.data.total;
    },
    async delEnterprise(id) {
      this.$confirm("确认删除该企业吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        await delEnterpriseApi(id);
        this.getEnterPriseList();
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
     delRent(id){
      this.$confirm('确定删除租赁合同吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delRentApi(id)
          this.getEnterPriseList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })       
    }
  },
};
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>
